package cn.ryanpenn.es.springclound.service.impl;

import cn.ryanpenn.es.springclound.service.CityService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * CityServiceImpl
 *
 * @author pennryan
 */
@Service
public class CityServiceImpl implements CityService {

    private Map<String, String> cityData = new HashMap<>(2444);

    @Override
    public void load() throws IOException {
        Resource resource = new ClassPathResource("citykey.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        String line;
        String[] pairDate;
        while ((line = reader.readLine()) != null) {
            pairDate = line.split(",");
            if (pairDate.length == 2) {
                cityData.put(pairDate[1], pairDate[0]);
            }else{
                // 碰到空行就停止.（仅用于开发调试,避免文件过大,耗费太多时间）
                break;
            }
        }
        reader.close();
    }

    @Override
    public Map<String, String> getCityData() {
        if (cityData.isEmpty()) {
            try {
                load();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return cityData;
    }
}
